package com.youlin.untils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MyBeanUtil {

    public static boolean isParamError (Object bean) {
        if (bean == null) return true;
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        List<String> nullAbleFields = Arrays.asList(declaredFields).parallelStream()
                .filter(field -> field.getAnnotation(Nullable.class) != null)
                .map(Field::getName).map(String::toLowerCase).collect(Collectors.toList());
        Method[] declaredMethods = bean.getClass().getDeclaredMethods();
        return Arrays.asList(declaredMethods).parallelStream()
                .filter(method -> method.getName().startsWith("get"))
                .filter(method -> ! nullAbleFields.contains(method.getName()
                        .replace("get", "").toLowerCase()))
                .anyMatch(method -> {
                    try {
                        Class<?> returnType = method.getReturnType();
                        if (returnType == String.class) {
                            String invoke = (String) method.invoke(bean);
                            return StringUtils.isBlank(invoke);
                        }
                        if (returnType == List.class) {
                            List invoke = (List) method.invoke(bean);
                            return invoke.size() == 0;
                        }
                        Object invoke = method.invoke(bean);
                        return invoke == null;
                    } catch (Exception e) {
                        return true;
                    }
                });
    }

    public static <T> T copyProperties (Object source, Class<T> tClass) {
        try {
            if (tClass == null) return null;
            T instance = tClass.newInstance();
            BeanUtils.copyProperties(source, instance);
            return instance;
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean isNotEmpty (List list) {
        return list != null && list.size() > 0;
    }

    public static boolean isEmpty (List list) {
        return list == null || list.size() == 0;
    }

}
